from flask import Flask, request, render_template, jsonify
from jieba.analyse.analyzer import ChineseAnalyzer
from whoosh.index import create_in, open_dir, exists_in
from whoosh.fields import Schema, ID, TEXT, DATETIME
from whoosh.qparser import QueryParser, MultifieldParser
from whoosh.query import DateRange, And
import json
from datetime import datetime


app = Flask(__name__)
host = "127.0.0.1"
port = "8080"
debug = True

# 加载索引
ix = open_dir("demo_ix", indexname="demo")
schema = ix.schema

# 定义一个默认字段
def get_defult_configure(field_name):
    return {
        "name":field_name,
        "showName":False,
        "showInTitle":False,
        "showInSubTitle":False,
        "showInContent":False,
        "isOption": False,
        "isSelected": False,
        "isUrl": False,
        "isDate": False,
        }

# 配置一些字段，没有配置的，会按默认进行设置
configure = ({
    "title": {
        "name":"标题",
        "showName": False,
        "isOption":True,
        "isSelected": True,
        "showInTitle":True,
        },
    "author": {
        "name":"作者",
        "showName": True,
        "isOption":True,
        "showInSubTitle":True,
        },
    "date": {
        "name":"发布时间",
        "showName": True,
        "showInSubTitle":True,
        "isOption":False,
        "isSelected": False,
        "isDate": True,
        },
    "content": {
        "name":"正文",
        "showInContent":True,
        "isOption":True,
        "isSelected": True
        },
    "url":{
        "isUrl": True
    }
})




# 所有字段的默认设置
defult_configure = {}
for i in schema.items():
    defult_configure[i[0]] = get_defult_configure(i[0])

# 用人工设置的configure覆盖defult_configure,得到最终的final_configure
final_configure = defult_configure
for k,v in configure.items():
    if k in final_configure:
        for vk,vv in v.items():
            if vk in final_configure[k]:
                final_configure[k][vk] = vv


def resultsPage2Json(resultsPage):
    rls = []
    for result in resultsPage:
        r = {}
        for k,v in final_configure.items():
            if ix.schema[k].stored == True:
                r[k] = result[k]
        rls.append(r)
    return  rls

@app.route('/search',methods=["POST"])
def search():
    postJson = request.get_json()
    with ix.searcher() as searcher:
        fields = postJson["fields"]
        word = postJson["word"]
        pagenum = postJson["pagenum"]
        pagelen = postJson["pagelen"]
        date_field = postJson["date_field"]
        date_start = datetime.strptime( postJson["date_start"][0:19], '%Y-%m-%dT%H:%M:%S')
        date_end = datetime.strptime( postJson["date_end"][0:19] , '%Y-%m-%dT%H:%M:%S')
        dateRangeQuery = DateRange(date_field, date_start, date_end)
        query = MultifieldParser(fields, ix.schema).parse(word)
        q = And([query, dateRangeQuery])
        rsPage = searcher.search_page(q,pagenum,pagelen)
        rsJson = resultsPage2Json(rsPage)
        rs = {
            "datasets": rsJson,
            "is_last_page": rsPage.is_last_page()
            }
        return jsonify(rs)

@app.route('/',methods=["GET"])
@app.route('/index',methods=["GET"])
def index():
    return render_template("index.html", config=final_configure)

if __name__ == '__main__':
    app.run(host, port, debug)
